<template>
  <ych-modal
    :fullscreen="true"
    :title="title"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel">

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row>
          <a-col :span="7">
            <a-form-item :label="$t('m.eform.appview.entity.viewName')" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="[ 'viewName', validatorRules.viewName]" placeholder=""></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="7">
            <a-form-item :label="$t('m.eform.appview.entity.viewCode')" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="[ 'viewCode', validatorRules.viewCode]" placeholder=""></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item :label="$t('m.eform.appform.entity.objectName')" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <object-code-tag v-decorator="[ 'objectCode', validatorRules.objectCode]" :placeholder="$t('m.eform.formDesign.label.qing-xuan-ze-er-mo-xing')"
                               :radio="false"
                               :groupId="groupId">
                <a-tooltip slot="addonAfter">
                  <template slot="title">
                    {{ $t('m.eform.formDesign.label.yong-yu-she-zhi-lie-biao-jian-de-lian-dong-guan-xi') }} </template>
                  <ych-icon type="question"/>
                </a-tooltip>
              </object-code-tag>
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item :label="$t('m.common.label.sort')" :labelCol="labelCol2" :wrapperCol="wrapperCol2">
              <a-input-number v-decorator="[ 'orderNum', validatorRules.orderNum]"></a-input-number>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>

      <view-layout-row :rows="layout" :height="height" :editable="true" @selectViewOk="selectViewOk"
                       :groupId="groupId"></view-layout-row>

    </a-spin>

    <template slot="footer">
      <a-button key="back" @click="handleCancel">{{ $t('m.common.button.close') }}</a-button>
      <a-button key="showTemplate" @click="showTemplateDrawer">{{$t('m.eform.formDesign.label.useTemplate')}}</a-button>
      <a-button key="preview" @click="handleOpenPreviewModal">{{$t('m.common.button.preview')}}</a-button>
      <a-button key="submit" type="primary" @click="handleOk">{{ $t('m.common.button.ok') }}</a-button>
    </template>

    <view-template-drawer ref="templateDrawer" @selectOk="selectTemplateOk" :groupId="groupId"></view-template-drawer>

    <layout-preview ref="layoutPreview" type="layout"></layout-preview>
  </ych-modal>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import ViewTemplateDrawer from './actAppView/ViewTemplateDrawer'
  import ViewLayoutRow from './actAppView/ViewLayoutRow'
  import ObjectCodeTag from '../select/tag/ObjectCodeTag'
  import YchConstant from "@/api/YchConstant";
  import LayoutPreview from "../layoutMaking/LayoutPreview";

  export default {
    name: 'ActAppViewLayoutModal',
    components: {
      ViewLayoutRow,
      ViewTemplateDrawer,
      ObjectCodeTag,
      LayoutPreview,
    },
    props: {
      groupId: {
        type: String,
        required: true
      },
    },
    data () {
      return {
        form: this.$form.createForm(this),
        title: this.$t('m.common.label.operate'),
        visible: false,
        model: {},
        height: document.body.clientHeight - 53 - 233 + 64,
        /*height: document.body.clientHeight - 53 - 55 - 114 + 'px',*/
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        labelCol2: {
          xs: {span: 24},
          sm: {span: 12}
        },
        wrapperCol2: {
          xs: {span: 24},
          sm: {span: 12}
        },
        confirmLoading: false,
        validatorRules: {
          viewName: { rules: [{ required: true, message: this.$t('m.eform.appview.verify.viewName') },] },
          viewCode: {
            rules: [{ required: true, message: this.$t('m.eform.appview.verify.viewCode') },
              { validator: this.checkCode }]
          },
          objectCode: {},
          orderNum: {
            initialValue: 1 // TODO 默认值取数据库最大值+10
          },
        },
        url: {
          add: YchConstant.PREFIX_EFORM + '/manage/actAppView/add',
          edit: YchConstant.PREFIX_EFORM + '/manage/actAppView/edit',
          checkCode: YchConstant.PREFIX_EFORM + '/manage/actAppView/checkCode',
        },
        layout: [],
      }
    },
    methods: {
      selectViewOk (record) {
        const viewName = this.form.getFieldValue('viewName')
        const viewCode = this.form.getFieldValue('viewCode')
        if (!viewName && record.viewName) {
          this.form.setFieldsValue({ viewName: record.viewName })
        }
        if (!viewCode && record.viewCode) {
          this.form.setFieldsValue({ viewCode: record.viewCode + '_layout' })
        }
      },
      add () {
        this.edit({})
      },
      edit (record) {
        this.form.resetFields()
        this.model = Object.assign({}, record)
        let layout = this.model.viewLayoutl ? JSON.parse(this.model.viewLayoutl) : [{
          cols: [{
            span: 24
          }]
        }]
        this.layout = this.initViewInfo(layout)
        this.visible = true
        this.$nextTick(() => {
          this.form.setFieldsValue(this.lodash.pick(this.model, 'viewName', 'viewCode', 'objectCode', 'orderNum'))
        })
      },
      copy (record) {
        this.form.resetFields()
        this.model = Object.assign({}, record)
        this.model.id = undefined
        let layout = this.model.viewLayoutl ? JSON.parse(this.model.viewLayoutl) : [{
          cols: [{
            span: 24
          }]
        }]
        this.layout = this.initViewInfo(layout)
        this.visible = true
        this.$nextTick(() => {
          this.form.setFieldsValue(this.lodash.pick(this.model, 'viewName', 'viewCode', 'objectCode', 'orderNum'))
        })
      },
      handleOk () {
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            let httpurl = ''
            let method = ''
            if (!this.model.id) {
              httpurl += this.url.add
              method = 'post'
            } else {
              httpurl += this.url.edit
              method = 'put'
            }
            let formData = Object.assign(this.model, values)
            formData.groupId = this.groupId
            formData.viewLayoutl = JSON.stringify(this.layout)
            formData.viewType = 'layout'
            this.confirmLoading = true
            httpAction(httpurl, formData, method).then((res) => {
              if (res.success) {
                this.messageUtil.success(res.message)
                this.$emit('ok')
                this.close()
              } else {
                this.messageUtil.warning(res.message)
              }
            }).finally(() => {
              this.confirmLoading = false
            })
          }
        })
      },
      handleCancel () {
        this.close()
      },
      close () {
        this.$emit('close')
        this.visible = false
      },
      showTemplateDrawer () {
        this.$refs.templateDrawer.visible = true
      },
      handleOpenPreviewModal() {
        this.$refs.layoutPreview.objectCode = this.form.getFieldValue('objectCode')
        this.$refs.layoutPreview.jsonData = {layout : this.layout}
        this.$refs.layoutPreview.show();
      },
      selectTemplateOk (tempBodyString) {
        let layout = tempBodyString ? JSON.parse(tempBodyString) : [{
          cols: [{
            span: 24
          }]
        }]
        this.layout = this.initViewInfo(layout)
      },
      initViewInfo (rows) {
        rows.forEach(row => {
          row.cols.forEach(col => {
            if (col.hasOwnProperty('rows')) {
              col.rows = this.initViewInfo(col.rows)
            } else if (col.hasOwnProperty('tabs')) {
              col.tabs.forEach(tab => {
                if (!tab.hasOwnProperty('viewItem')) {
                  tab.viewItem = {
                    viewName: 'm.eform.formDesign.label.Tab',
                    viewCode: '',
                    viewType: ''
                  }
                }
              })
            } else {
              if (!col.hasOwnProperty('viewItem')) {
                col.viewItem = {
                  viewName: '',
                  viewCode: '',
                  viewType: ''
                }
              }
            }
          })
        })
        return rows
      },
      checkCode (rule, value, callback) {
        if (!value) {
          callback()
          return
        }
        let reg = new RegExp("[\\u4E00-\\u9FFF]+","g");
        if(reg.test(value)){
          callback(this.$t('m.common.tip.code_format'))
          return
        }
        getAction(this.url.checkCode, {
          value: value,
          id: this.model.id
        }).then((res) => {
          res.success ? callback() : callback(res.message)
        })
      }
    }
  }
</script>
